package cn.ccccltd.waf.message.email.provider;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSONObject;

import cn.ccccltd.waf.message.base.provider.BaseMessageService;
import cn.ccccltd.waf.message.email.properties.EmailProperties;
import cn.ccccltd.waf.message.model.result.MessageResult;
import cn.ccccltd.waf.message.model.vo.MessageEmail;
import cn.ccccltd.waf.message.util.CopyMessage;
import cn.ccccltd.waf.message.util.DateUtilsNew;
import cn.ccccltd.waf.message.util.JsonUtils;
import cn.ccccltd.waf.message.util.ToolUtils;

/**
 * 创建日期:2017年10月31日
 * Title:生产者
 * Description：对本文件的详细描述，原则上不能少于50字
 * @author yangjingjiang
 * @mender：（文件的修改者，文件创建者之外的人）
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@SuppressWarnings("rawtypes")
@Component("email")
public class EmailProvider extends BaseMessageService{

	@Autowired
	EmailProperties emailProperties;
	
	/**JmsTemplate必须要用resource,且固定注入名称*/
	@Resource(name="emailJmsTemplate")
	private JmsTemplate emailTemplate;
	
	
	
	@Override
	protected String getTableName() {
		return "waf_msg_email";
	}

	@Override
	protected Class getEntityClass() {
		return MessageEmail.class;
	}
	
	@Override
	protected JmsTemplate getJmsTemplate() {
		return emailTemplate;
	}
	
	/**
	 * 功能: 邮件发送队列及保存消息表<br>
	 * 作者: yangjingjiang <br>
	 * 创建日期:2017年11月14日 <br>
	 * 修改者: mender <br>
	 * 修改日期: modifydate <br>
	 * @param content
	 * @return
	 * @see cn.ccccltd.waf.message.base.provider.BaseMessageService#sendMessage(com.alibaba.fastjson.JSONObject)
	 */
	@SuppressWarnings({ "unchecked"})
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Object sendMessage(JSONObject content) {
		
		MessageResult result = new MessageResult();
		
		MessageEmail emailMessage = JsonUtils.toObject(content.toJSONString(), MessageEmail.class);
		
		Assert.hasText(emailMessage.getMsgTopic(), "邮件的主题不能为空！");
		Assert.hasText(emailMessage.getContent(), "邮件的内容不能为空！");
		
		//如果发送时间没有或者是null进行相应填值处理
		if (StringUtils.isBlank(emailMessage.getSendTime())) {
			emailMessage.setSendTime(DateUtilsNew.getDateTime());
		}
		
		//消息队列消息统一发送
		List<MessageEmail> msgListQueue = new ArrayList<>();
		
		insertMessageSuperTable(emailMessage);
		//将消息父id放到关联id上
		emailMessage.setCommonId(emailMessage.getId());
		
		emailMessage.setCreateTime(DateUtilsNew.getDateTime());
		
		String emailAddresss = emailMessage.getEmailAddress().trim();
		
		Assert.hasText(emailAddresss, "邮件地址不能为空！");
		
		//插入消息
		if (emailAddresss.contains(",")) {
			
			CopyMessage cm = new CopyMessage();
			for (String emailAddress : emailAddresss.split(",")) {
				
				Assert.isTrue(ToolUtils.isEmail(emailAddress), emailAddress + "邮箱地址不合法！");
				
				MessageEmail wme = new MessageEmail();
				//cglib拷贝对象
				cm.copyBean(emailMessage, wme);
				wme.setEmailId(ToolUtils.getUUID());
				wme.setEmailAddress(emailAddress);
				insertMessageTable(wme);
				msgListQueue.add(wme);
			}
			
		} else {
			
			Assert.isTrue(ToolUtils.isEmail(emailAddresss), emailAddresss + "邮箱地址不合法！");
			
			emailMessage.setEmailAddress(emailAddresss);
			insertMessageTable(emailMessage);
			msgListQueue.add(emailMessage);
			
		}
		
		//发送消息到消息队列
		if (msgListQueue.size()>0) {
			
			return sendMessageByThread(msgListQueue, emailProperties.getGroupSize());
			
		}
		
		result.setSuccess("false");
		result.setStateCode("500");
		result.setMsg("队列发送失败，请联系管理员！");
		
		return result;
	}

}
